package com.carlos.company.security.service;

import com.carlos.company.pojo.SysUser;
import com.carlos.company.service.SysUserRoleService;
import com.carlos.company.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 李健成
 * @date 2021/10/13
 */

@Slf4j
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;
    private final SysUserRoleService sysUserRoleService;

    @Autowired
    public MyUserDetailsServiceImpl(SysUserService sysUserService, SysUserRoleService sysUserRoleService) {
        this.sysUserService = sysUserService;
        this.sysUserRoleService = sysUserRoleService;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        log.info("开始执行 loadUserByUsername ...");

        // 查询用户
        SysUser user = sysUserService.getByUsername(s);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 查询角色
        List<GrantedAuthority> authorities = new ArrayList<>(2);
        for (String role : sysUserRoleService.listRoleCodeByUsername(s)) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        user.setAuthorities(authorities);

        log.info("loadUserByUsername 完成 : {}", user);

        return user;
    }

}
